<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>发送超时请求</button>
    <button id="btn2">取消请求</button>
    <script>
        const btn = document.querySelector('button');
        const btn2 = document.querySelector('#btn2');
        let xhr;

        btn.onclick = function(){
            //判断请求是否正在发送
            if(xhr){
                xhr.abort();
            }
            xhr = new XMLHttpRequest();
            xhr.open('GET','http://127.0.0.1/delay-server');
            xhr.send();
            //超时时间设置
            xhr.timeout = 3000;
            xhr.ontimeout = function(){
                alert('对不起 请求超时, 请重试!!');
            }
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4) {
                    if(xhr.status >= 200 && xhr.status < 300){
                        console.log(xhr.response);
                    }
                }
            }
        }
        
        //点击取消请求
        btn2.onclick = function(){
            //调用方法取消
            xhr.abort();
        }
    
    </script>
</body>
</html>